let domTRarr = [];
let nodeActive = null;
let currentSeleRow = 0;
let resData = null;

$NG.AllReady(function (page, { useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange, useClick, useBeforeClick }) {
  // 编辑页面逻辑
  const mstform = $NG.getCmpApi("p_form_integrated_apply_m");
  const grid1 = $NG.getCmpApi("p_form_integrated_apply_d1");
  const grid2 = $NG.getCmpApi("p_form_integrated_apply_d2");
  const getItemValue = (itemName) => mstform.getItem(itemName).getValue(); //表头字段属性设置

  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////



  //   insertitemdataByDJPhid(@u_item_name, @u_item_sub, @u_spec, @u_unit);
  const { origin, pathname } = window.location;
  let reqTimeLock = 0
  let timeMax = 0
  useBeforeClick(({ args }) => {
    $NG.message("正在匹配 0.1% 请耐心等待~~~")
    window.stertNum = 0
    window.endNum = 0
    window._list = []
    reqTimeLock = setInterval(() => {
      if (window.stertNum == window.endNum) {
        //可以请求了
        $NG.message(`正在匹配 ${(stertNum / (grid1.getRows().length * 2.5)).toFixed(4) * 100}% 请耐心等待~~~`)
        const list = removeDuplicatesByKeys(window._list)
        // console.log(`数据准备就绪：`, list);
        if (list.length == 0) {
          $NG.alert("匹配完成！ 100%");
        } else {
          getWlRequest(list)
        }
        clearInterval(reqTimeLock)
      } else {
        window.endNum = window.stertNum
      }
    }, 1000)
    matchingMaterial()
  }, "user_match")

  //去重
  function removeDuplicatesByKeys(arr) {
    const uniqueMap = new Map();
    for (const obj of arr) {
      // 生成一个由 ItemName、PhidResbs 和 PhidMsunit 组合而成的唯一键
      const key = `${obj.ItemName}-${obj.Spec}-${obj.PhidMsunit}`;
      if (!uniqueMap.has(key)) {
        // 如果该键还未存在于 Map 中，则将对象存入
        uniqueMap.set(key, obj);
      }
    }
    // 将 Map 中的值（即去重后的对象）提取到一个新数组中
    return Array.from(uniqueMap.values());
  }

  //匹配物料主请求
  async function getWlRequest(list) {
    // const response = await fetch("http://nginx.clouddev.hisense.com/sd/interior/createResourceFileSync", {
    //   method: "POST",
    //   headers: {
    //     "Content-Type": "application/json", // 设置请求头
    //   },
    //   body: JSON.stringify(list),
    // });
    const response = await fetch("https://inner-apisix.hisense.com/hisense/sd/common/interior/createResourceFileSync?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6 ", {
      method: "POST",
      headers: {
        "Content-Type": "application/json", // 设置请求头
      },
      body: JSON.stringify(list),
    });
    const res = await response.json();
    // console.log(`请求数据`, res);
    if (res.IsOk) {
      //新增成功
      matchingMaterial(); //重新匹配
      [1, 2, 3].forEach((item) => {
        $NG.message(`正在重新匹配，请勿操作等待提示完成！！！%`);
      })
      timeMax = setTimeout(() => {
        $NG.alert("匹配超时！！！")
      }, 1000 * 90)
      $NG.alert("匹配完成！ 100%");
      clearTimeout(timeMax)
    } else {
      if (res.data == "批量新增失败，入参为空！") {
        $NG.alert("匹配完成，入参为空！");
      } else {
        $NG.alert("匹配错误！");
      }
    }
  }

  //按钮点击前事件
  useBeforeClick(async ({ args }) => {
    // console.log(`保存`);
    grid1.getRows().forEach((item, index) => {
      if (!item.itemid) {
        console.log(item.phid);
        // console.log("itemid", item.itemid);
        // console.log("u_item_name", item.u_item_name);
        // console.log("u_item_sub", item.u_item_sub);
        // console.log("u_spec", item.u_spec);
        // console.log("u_unit", item.u_unit);
        $NG.execServer("getItemDataByDJInfo", { u_item_name: "'" + item.u_item_name + "'", u_item_sub: item.u_item_sub, u_spec: "'" + item.u_spec + "'", u_unit: item.u_unit }, function (res) {
          //   console.log(res, "res");
          if (res.count > 0) {
            let data = JSON.parse(res.data)[0].extendObjects; //单返回值
            // console.log(data);
            $NG.execServer("UPDATE", { tbname: `p_form_integrated_apply_d1`, sqlStr: `phid_itemdata=${data.phid}`, queryStr: `phid = ${item.phid}` }, function (res) {
              //   console.log(res, "res");
              //   console.log("UPDATE");
            });
            grid1.refreshView();
          } else {
            $NG.execServer("InsertItemDataByDJPhid", { u_item_name: "'" + item.u_item_name + "'", u_item_sub: item.u_item_sub, u_spec: "'" + item.u_spec + "'", u_unit: item.u_unit }, function (res) {
              //   console.log(res, "res");
              //   console.log("InsertItemDataByDJPhid");
            });
          }
        });
      }
      //   console.log(grid1.getRows());

      grid1.refreshView();
    });
    const _arr = []
    grid1.getRows().forEach((item, index) => {
      if (!(String(item.u_item_name || "") || "").trim() ||
        !(String(item.u_unit || "") || "").trim() ||
        !(String(item.u_spec || "") || "").trim() ||
        !(String(item.u_item_sub || "") || "").trim() || !item.u_item_no) {
        _arr.push(index + 1)
        // console.log(`有满足的`);
      }
    })
    if (_arr.length !== 0) {
      $NG.alert(`明细第 ${_arr.join("、")} 行不满足物料条件，编码、名称、规格、单位、小类有空！`)
      return false
    }
  }, "save");

  const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_integrated_apply_d1");
  if (toolbar_dgrid) {
    toolbar_dgrid.insert({
      id: "template_download",
      text: "模板下载",
      iconCls: "icon-InsertRow",
    });

    useClick(async function ({ args }) {
      const url = `${origin}/report/index.html#/tableDesign/TableManager/preview?rep_id=8570000000000010&multiCooperate=0&busCode=null&menucode=82463aa3-e537-7190-0d98-81415c46dace&AppTitle=%E5%AE%9A%E4%BB%B7%E7%94%B3%E8%AF%B7%E6%8A%A5%E8%A1%A8`;
      // const url = `${origin}/report/index.html#/tableDesign/TableManager/preview?${queryString}`;
      console.log(url);
      // 打开报表并传递参数
      $NG.open(url, { AppTitle: "报表查看" });
    }, "template_download");
  }

  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////

  if (mstform) {
    if (page.oType == "add") {
      mstform.getItem("u_sqlx").setValue("01");
    }
    useValuesChange(({ args }) => {
      //TODO
      //   console.log(args, "args");
      if (mstform.getValues().u_sqlx == "01") {
        //表头字段属性设置
        $NG.updateUI((updater) => {
          const fields = ["phid_pc", "u_regional_center", "u_product_line"];
          fields.forEach((field) => {
            // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
            updater.fieldSetForm.p_form_integrated_apply_m[field].setProps({
              hidden: true, //隐藏
            });
          });
        });
      } else {
        $NG.updateUI((updater) => {
          const fields = ["phid_pc", "u_regional_center", "u_product_line"];
          fields.forEach((field) => {
            // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
            updater.form.p_form_integrated_apply_m[field].setProps({
              hidden: false, //隐藏
            });
          });
        });
      }
    }, 'p_form_integrated_apply_m.u_sqlx');
    $NG.updateUI((updater, state) => {
      //   console.log(`过滤`, updater);
      updater.fieldSetForm.p_form_integrated_apply_m.u_bus_no.setProps({
        onDoubleClick() {
          //   console.log(`被点击了`);
          onT();
        },
      });
    });
  }

  if (page.oType == "add") {
    if ($NG.getCmpApi("p_form_integrated_apply_m")) {
      getPtInfoByPhid();
    }
  }

  /**
   *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
   */
  useValuesChange(({ args }) => {
    getPtInfoByPhid();
  }, "p_form_integrated_apply_m.phid_pc");
  useValuesChange(({ args }) => {
    setTimeout(() => {
      ajaxGet();
    }, 200);
  }, "p_form_integrated_apply_m.u_pc_pre_sales");
  /**
   *@license: 	 //u_sqlx	//u_sqlx
   */
  useValuesChange(({ args }) => {
    // console.log("args11", args);
  }, "p_form_integrated_apply_m.u_sqlx");
  /**
   *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
   */
  useValuesChange(({ args, instance }) => {
    // console.log("args111", args);
    calcCostRedRate();
  }, "p_form_integrated_apply_m.u_pur_amt");

  /**
   *@license:设备物资表 计算
   */
  function initUserType(_data) {
    _data.forEach((item) => {
      if (!item.u_dj_status) {
        item.u_dj_status = '1'
      }
    })
    grid1.refreshView()
  }
  if (page.oType == "view") {
    const rows = grid1.getRows();
    let endAmt = 0;
    let sqyj = 0;
    let jbl = 0;
    rows.forEach((row) => {
      endAmt += (Number(row.u_pur_prc) || 0) * (Number(row.u_qty) || 0);
      sqyj += (Number(row.u_pre_sale_amt) || 0) * (Number(row.u_qty) || 0)
    });

    console.log(sqyj, endAmt);
    let sqyj2 = mstform.getItem('u_sqyj_amt').getValue()
        console.log(`endAmt`,endAmt,sqyj2,sqyj);
    jbl = Number(((sqyj2 - endAmt) / sqyj).toFixed(4));
    console.log(jbl);
    mstform.getItem('u_cost_red_rate').setValue(jbl)
    $NG.updateState((updater) => {
      updater.data.p_form_integrated_apply_m.setProps({
        // u_sqyj_amt: sqyj,
        u_pur_amt: endAmt,
        // u_cost_red_rate: jbl,
      });
    });
  }
  Grid1();

  useDataIndexChange(({ args }) => {
    getItemdataByPhid(args[0])
  }, "u_item_no")

  useUpdateRows(({ args }) => {
    initUserType(args[0])
    Grid1();
    console.log(``,);

    //   if (row.u_wlbm_y && !row.u_item_no) {
    console.log("row.u_wlbm_y", row.u_wlbm_y);
    //     $NG.execServer("getItemdataByNo", { itemno: "'" + row.u_wlbm_y + "'" }, function (res) {
    //       if (res.count > 0) {
    //         let requestData = JSON.parse(res.data)[0].extendObjects; //单返回值
    console.log(requestData, "获取请求值");
    //         //物料名称
    //         row.u_item_name = requestData.itemname;
    //         //物料编码
    //         row.u_item_no = requestData.phid;
    //         row.u_item_no_EXName = requestData.itemno;
    //         //规格
    //         row.spec = requestData.spec;
    //         row.msunit = requestData.msunit_phid;
    //         row.msunit_EXName = requestData.msunit_name; //单位
    //         //物料分类
    //         row.u_item_sub = requestData.phid_resbs; //单位
    //         row.u_item_sub_EXName = requestData.name; //单位
    console.log("u_item_sub_EXName1");
    //         grid1.refreshView();
    //       } else {
    console.log("useUpdateRows没有找到拟采购清单"); // items.u_u_pur_item = null; // items.u_u_pur_item_EXName = null;
    //         mstform.setReadOnly("字段名称", false); //取消只读
    //         mstform.setReadOnly("字段名称", false); //取消只读
    //         mstform.setReadOnly("字段名称", false); //取消只读
    //         mstform.setReadOnly("字段名称", false); //取消只读
    //       }
    //     });
    //   }

    //   if (row.u_item_no) {
    //     $NG.execServer("getItemdataByPhid", { phid: row.u_item_no }, function (res) {
    //       const datas = JSON.parse(res.data)[0].extendObjects;
    console.log(datas, "xxxxxxxx");
    //       row.u_item_name = datas.itemname;
    //       row.spec = datas.spec;
    //       row.msunit = datas.msunit_phid;
    //       row.msunit_EXName = datas.msunit_name; //单位
    //       row.u_wlbm_y = row.u_item_no_EXName;

    console.log(row, "物料单个");
    console.log(row.msunit, row.u_item_name, row.spec, "?????");
    //       if (row.msunit && row.u_item_name && row.spec) {
    //         $NG.execServer(
    //           "getItemdataPhid",
    //           {
    //             phid_unit: row.msunit,
    //             itemname: `'${row.u_item_name}'`,
    //             spec: `'${row.spec}'`,
    //           },
    //           function (res) {
    //             const datas = JSON.parse(res.data)[0].extendObjects;
    console.log(datas.phid, "查询物料phid");
    console.log(datas, "查询物料phid");
    //             row.u_item_no = datas.phid;
    //             row.u_item_no_EXName = datas.itemno;
    console.log(row.u_item_no, "row..u_item_no");
    //             row.u_item_sub = datas.phid_resbs; //单位
    //             row.u_item_sub_EXName = datas.name; //单位
    //             // row.u_item_sub = datas.phid_resbs; //单位
    //             // row.u_item_sub_EXName = datas.name; //单位

    //             grid1.refreshView();
    //           }
    //         );
    //       }
    //       grid1.refreshView();
    //     });
    //   }

    // jbl = ((sqyj - endAmt) / sqyj).toFixed(4);
    // $NG.updateState((updater) => {
    //   updater.data.p_form_integrated_apply_m.setProps({
    //     u_sqyj_amt: sqyj,
    //     u_pur_amt: endAmt,
    //     u_cost_red_rate: jbl,
    //   });
    // });
  }, "p_form_integrated_apply_d1");

  //选物料带出单位等
  function getItemdataByPhid(item) {
    const phid = item.u_item_no
    $NG.execServer("getItemdataByPhid", { phid }, (res) => {
      if (res.count == 0) return
      const data = JSON.parse(res.data)[0].extendObjects
      item.u_unit = data.msunit_phid
      item.u_unit_EXName = data.msunit_name
      item.u_spec = data.spec
      item.u_item_sub = data.res_bs_phid
      item.u_item_sub_EXName = data.res_bs_name
      grid1.refreshView()
    })
  }

  function Grid1() {
    let sumAmt1 = 0;
    let sumAmt2 = 0;
    let sumAmt3 = 0;
    let sumAmt4 = 0;
    let rows = grid1.getRows();
    rows.forEach((row) => {
      sumAmt1 += calcTargetAmt(row.u_target_prc, row.u_qty); //  目标价格 *数量 = 目标价格金额;
      sumAmt2 += calcMarketAmt(row.u_prc, row.u_qty); //  市场价格 *数量 = 市场平均金额;
      sumAmt3 += calcPreSaleAmt(row.u_pre_sale_amt, row.u_qty); //  市场价格 *数量 = 售前议价金额;
      sumAmt4 = calcCostRedRate();
      if (!row.u_is_scbzwl) {
        row.u_is_scbzwl = "1";
        row.u_is_scbzwl_EXName = "是";
      }
      if (!row.u_rest_qty || row.u_rest_qty == 0) {
        row.u_rest_qty = row.u_qty;
      }
      //   console.log(row.u_dj_status);

      if (row.u_dj_status == 4) {
        $NG.updateUI((updater) => {
          const fields = ["u_bhyy"];
          fields.forEach((field) => {
            updater.editGrid.p_form_integrated_apply_d1[field].setProps({
              hidden: false,
            });
          });
        });
        grid1.refreshView()
      }

      if (row.u_wlbm_y && !row.u_item_no) {
        // console.log("row.u_wlbm_y", row.u_wlbm_y);
        $NG.execServer("getItemdataByNo", { itemno: "'" + row.u_wlbm_y + "'" }, function (res) {
          if (res.count > 0) {
            let requestData = JSON.parse(res.data)[0].extendObjects; //单返回值
            // console.log(requestData, "获取请求值");
            //物料名称
            row.u_item_name = requestData.itemname;
            //物料编码
            row.u_item_no = requestData.phid;
            row.u_item_no_EXName = requestData.itemno;
            //规格
            row.spec = requestData.spec;
            row.msunit = requestData.msunit_phid;
            row.msunit_EXName = requestData.msunit_name; //单位
            //物料分类
            row.u_item_sub = requestData.phid_resbs; //单位
            row.u_item_sub_EXName = requestData.name; //单位
            // console.log("u_item_sub_EXName1");
            grid1.refreshView();
          } else {
            // console.log("useUpdateRows没有找到拟采购清单"); // items.u_u_pur_item = null; // items.u_u_pur_item_EXName = null;
            mstform.setReadOnly("字段名称", false); //取消只读
            mstform.setReadOnly("字段名称", false); //取消只读
            mstform.setReadOnly("字段名称", false); //取消只读
            mstform.setReadOnly("字段名称", false); //取消只读
          }
        });
      }
      if (!row.phid_itemdata || !row.itemid || !row.phid_resbs) {
        $NG.execServer(
          "getItemDataByDJInfo",
          {
            u_item_name: "'" + row.u_item_name + "'",
            u_item_sub: row.u_item_sub,
            u_spec: "'" + row.u_spec + "'",
            u_unit: row.u_unit,
          },
          function (res) {
            // console.log(res, "res");
            if (res.count > 0) {
              let data = JSON.parse(res.data)[0].extendObjects; //单返回值
              //   console.log(data);
              // row.phid_itemdata = data.phid;
              // row.phid_itemdata_EXName = data.itemname;
              // row.itemid = data.ps_resbase_phid;
              // row.itemid_EXName = data.itemname;
              // row.itemname = data.itemname;
              // row.itemno = data.itemno;
              // row.u_item_no = data.itemno;
              // row.phid_resbs = data.phid_resbs;
              $NG.execServer("UPDATE", { tbname: `p_form_integrated_apply_d1`, sqlStr: `phid_itemdata=${data.phid},itemid=${data.ps_resbase_phid},phid_resbs=${data.phid_resbs}`, queryStr: `phid = ${row.phid}` }, function (res) {
                // console.log(res, "res");
                // console.log("UPDATE");
              });
              grid1.refreshView();
            }
          }
        );
      }

      if (row.u_item_no && !row.phid_itemdata) {
        $NG.execServer("getItemdataByPhid", { phid: row.u_item_no }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          //   console.log(datas, "xxxxxxxx");

          row.u_item_name = datas.itemname;
          row.spec = datas.spec;
          row.msunit = datas.msunit_phid;
          row.msunit_EXName = datas.msunit_name; //单位
          row.u_wlbm_y = row.u_item_no_EXName;

          //   console.log(row, "物料单个");
          //   console.log(row.msunit, row.u_item_name, row.spec, "?????");
          if (row.msunit && row.u_item_name && row.spec) {
            $NG.execServer(
              "getItemdataPhid",
              {
                phid_unit: row.msunit,
                itemname: `'${row.u_item_name}'`,
                spec: `'${row.spec}'`,
              },
              function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                // console.log(datas.phid, "查询物料phid");
                // console.log(datas, "查询物料phid");
                row.u_item_no = datas.phid;
                row.u_item_no_EXName = datas.itemno;
                // console.log(row.u_item_no, "row..u_item_no");
                row.u_item_sub = datas.phid_resbs; //单位
                row.u_item_sub_EXName = datas.name; //单位
                // row.u_item_sub = datas.phid_resbs; //单位
                // row.u_item_sub_EXName = datas.name; //单位

                grid1.refreshView();
              }
            );
          }
          grid1.refreshView();
        });
      }

      //汇总赋值
      $NG.updateState((updater) => {
        updater.data.p_form_integrated_apply_m.setProps({
          u_tar_amt: sumAmt1,
          u_ave_amt: sumAmt2,
          u_sqyj_amt: sumAmt3,
          // u_cost_red_rate: sumAmt4,
        });
      });
    });
  }

  /**
   *@function:带出项目信息
   */
  function getPtInfoByPhid() {
    if (mstform.getItem("phid_pc").getValue()) {
      $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        // console.log(datas, "datas");
        //帮助字段赋值
        $NG.updateState((updater) => {
          updater.data.p_form_integrated_apply_m.setProps({
            // u_supply_att: datas.u_supply_att, //计划完工日期
            // u_supply_name: datas.u_supply_name, //计划竣工日期
            u_pc_no: datas.pc_no, //项目编码
            phid_org: {
              //事业部or组织
              value: datas.org_phid,
              label: datas.org_name,
            },
            u_regional_center: {
              //区域中心
              value: datas.regional_center_phid,
              label: datas.regional_center_name,
            },
            u_product_line: {
              //产品线
              value: datas.midwife_phid,
              label: datas.midwife_name,
            },
            u_pc_pre_sales: {
              value: datas.user_sqgw_phid,
              label: datas.user_sqgw_name, //销售顾问
            },
            u_department: {
              value: datas.dept_phid,
              label: datas.dept_name, //部门
            },
            bill_name: mstform.getValues().phid_pc_EXName + "定价申请",
          });
          setTimeout(() => {
            ajaxGet();
          }, 200);
        });
        $NG.execServer("projectSjbm", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;

          if (datas.user_sjbm) {
            $NG.execServer("isYzPush", { sjno: `'${datas.user_sjbm}'` }, function (res1) {
              try {
                if (res1.data > 0) {
                  const datas1 = JSON.parse(res1.data)[0].extendObjects;
                  //   console.log(datas1, "datas1"); //判断是否已推送
                  $NG.updateState((updater) => {
                    updater.data.p_form_integrated_apply_m.setProps({
                      u_is_yztj: { value: 1, label: "是" },
                    });
                  });
                } else {
                  //   console.log(res1.data, "res1.data");
                  $NG.updateState((updater) => {
                    updater.data.p_form_integrated_apply_m.setProps({
                      u_is_yztj: { value: 2, label: "否" },
                    });
                  });
                }
              } catch (error) {
                // console.log(error, "isYzPush??");
              }
            });
          } else {
            $NG.updateState((updater) => {
              updater.data.p_form_integrated_apply_m.setProps({
                u_is_yztj: { value: 2, label: "否" },
              });
            });
          }

          $NG.updateState((updater) => {
            updater.data.p_form_integrated_apply_m.setProps({
              u_bus_no: datas.user_sjbm, //项目编码
              u_sj_name: datas.user_sjmc, //项目名称
            });
          });
        });
      });
    }
  }

  // 增加匹配物料
  if (page.oType != 'view') {
    toolbar_dgrid.insert({
      id: "user_match",
      text: "匹配物料",
      iconCls: "icon-InsertRow",
    });
  }

  //匹配物料
  function matchingMaterial() {
    const d1arr = grid1.getRows()
    d1arr.forEach((item, index) => {
      if (!(String(item.u_item_name) || "").trim() ||
        !(String(item.u_unit) || "").trim() ||
        !(String(item.u_spec) || "").trim() ||
        !(String(item.u_item_sub) || "").trim()) { } else {
        $NG.execServer(
          "getItemDataByName",
          {
            itemname: `'${item.u_item_name}'`,
            spec: `'${item.u_spec}'`,
            msunit: `'${item.u_unit}'`,
          },
          function (res) {
            // console.log(item.u_item_name, item.u_spec, item.u_unit, res);
            window.stertNum += 1
            if (res.count > 0) {
              const data = JSON.parse(res.data)[0].extendObjects
              //   console.log('编码查询', data, data.itemno);
              item.u_item_no_EXName = data.itemno;
              item.u_item_no = data.phid;
              grid1.refreshView()
            } else {
              $NG.execServer("getResBsByphid", { phid: item.u_item_sub }, (res2) => {
                window.stertNum += 1
                const _data = JSON.parse(res2.data)[0].extendObjects
                window._list.push({
                  ItemName: item.u_item_name,
                  PhidResbs: item.u_item_sub,
                  PhidMsunit: item.u_unit,
                  Spec: item.u_spec,
                  ResBsCode: item.u_item_sub, // 假设 ResBsCode 是固定值，需根据实际情况调整
                  ResourceType: _data.resource_type, // 假设资源类型是固定的
                });
              })

            }
          }
        );
      }

    });
  }

  /**
   *@function:目标价格金额 计算
   */
  function calcTargetAmt(targePrice, num) {
    return targePrice * num;
  }

  /**
   *@function:市场平均金额 计算
   */

  function calcMarketAmt(targePrice, num) {
    return targePrice * num;
  }
  /**
   *@function:售前议价金额 计算
   */
  function calcPreSaleAmt(targePrice, num) {
    return targePrice * num;
  }

  /**
   *@function:降成本率 计算
   */
  function calcCostRedRate() {
    // 获取值并校验
    const sqyjAmt = parseFloat(getItemValue("u_sqyj_amt")) || 0; // 售前议价金额
    const purAmt = parseFloat(getItemValue("u_pur_amt")) || 0; // 最终采购价格

    // 检查售前议价金额是否为 0
    if (sqyjAmt === 0) {
      console.error("售前议价金额为 0 或无效，无法计算。");
    } else {
      // 计算差额百分比
      const percentageDiff = (sqyjAmt - purAmt) / sqyjAmt;
      //   console.log("差额百分比：", percentageDiff);

      // 如果需要输出百分比格式
      const percentageFormatted = (percentageDiff * 100).toFixed(2);
      //   console.log("格式化结果：", percentageFormatted + "%");

      $NG.updateState((updater) => {
        updater.data.p_form_integrated_apply_m.setProps({
          // u_cost_red_rate: percentageFormatted,
        });
      });
    }
  }

  /**
   *@function:损失率 计算
   */

  function calcLossRate() {
    // 获取值并校验
    const sqyjAmt = parseFloat(getItemValue("u_sqyj_amt")) || 0; // 售前议价金额
    const purAmt = parseFloat(getItemValue("u_ave_amt")) || 0; // 市场平均金额
    return sqyjAmt - purAmt;
  }
  // // /10.表体数据变化（增行、删行、引入）时，汇总计算至表头
  // useUpdateRows(({ args }) => {
  // 	var sumAmt = 0;
  // 	const rows = args[0];
  // 	rows.forEach((items) => {
  // 		if (items.u_target_prc && items.u_qty) {
  // 			sumAmt += parseFloat(items.u_target_prc * items.u_qty);
  // 		}
  // 		//汇总赋值
  // 		$NG.updateState((updater) => {
  // 			updater.data.p_form_integrated_apply_m.setProps({
  // 				u_tar_amt: sumAmt,
  // 			});
  // 		});
  // 	});
  // }, "p_form_integrated_apply_d1");
});

//表体u_qty*u_pur_prc=表头u_pur_amt

//表体u_qty*u_prc=表头u_ave_amt
// 获取商机信息
function getSjhInfo(no) {
  if (!no) return
  const mstform = $NG.getCmpApi("p_form_integrated_apply_m");
  $NG.execServer("getSjhInfo", { no }, (res) => {
    if (res.count == 0) return
    const _data = JSON.parse(res.data)[0].extendObjects
    $NG.updateState((updater) => {
      updater.data.p_form_integrated_apply_m.setProps({
        u_regional_center: {
          label: _data.u_regional_center_exname,
          value: _data.u_regional_center
        },
        u_product_line: {
          label: _data.u_product_line_exname,
          value: _data.u_product_line
        }
      })
    })
  })
}
const style = document.createElement("style"); // 创建一个新的 <style> 元素
const cssRules = `
 
        .zdy-bigBox{
            background:white;
            width: 60vw;
            height:60vh;
            top:15vh;
            left:20vw;
            border-radius:4px;
        }
        .zdy-tableHeader{
            border-bottom:1px #d3d3d3 solid;
            padding:1vh 0 ;
            display:flex;
            justify-content: space-between;
        }
        .zdy-header-button{
            width:35%;
        }
        .zdy-header-button input{
            border:1px #d3d3d3 solid;
            border-radius: 4px;
            height:100%;
            width:80%;
            font-size:40%;
            outline: none;
            padding-left:2px;
        }
        .zdy-header-button button{
            width:2vw;
            height:2vw;
        }
        .zdy-title{
            border-left:4px #1677ff solid;
            padding:0 0 0 0.5vw ;
        }
        .header{
            display:flex;
        }
        /* tabs */
        .zdy-tabs-box{
            width:100%;
            height:8%;
            border:1px green solid;
        }
        .zdy-tabs-box ul{
            width:auto;
            height:100%;
            padding-left:2%;
            display:flex;
            list-style: none;
            font-size:90%;
            align-items:end;
        }
        .zdy-tabs-box li{
            height:auto;
            margin-right:10%;
            border-bottom:#1677ff solid 2px;
        }
        .zdy-table{
            width:100%;
            border-collapse: collapse;
            overflow:hidden;
            text-align:left;
            background:#fff;
        }
        .zdy-table-box{
            margin:1% auto;
            width:98%;
            height:80%;
            overflow-y:scroll;
        }
        .zdy-table tr{
            height: 30px;
            border-bottom:1px #d0d0d0 solid;
            /*border:1px black solid;*/
            transition: all 0.2s linear;
        }
        .zdy-table td,.zdy-table th{
            padding:1.5% 0;
            /*border:1px black solid;*/
        }
        .zdy-table-thead-tr,zdy-table-tbody-tr{
            vertical-align: top;
        }
        .zdy-table-thead-tr th{
            height:10px;
        }
        .zdy-col-box{
            width:100%;
            display:none;
            height:5%;
            ul{
                list-style: none;
                display:flex;
            }
        }
        .zdy-box-page{
            width:100%;
            display:flex;
        }
        .zdy-btn-ok{
            width:100%;
            height:5%;
            display:flex;
            justify-content: end;
        }
        .zdy-btn-ok button{
            margin-right:5%;
            width:6vw;
        }
        .zdy-btn-box{
            display:flex;
        }
            .zdy-active{
            background-color: hsl(215, 100%, 94%);
        }
            #zdy-main{
                background:#0000007a;
                width:100%;
                height:100vh;
                position:fixed;
                top:0;
                left:0;
                z-index:999;
                display:none;
                justify-content: center;
                align-items:center
            }
`;
style.textContent = cssRules; // 设置 <style> 元素的内容为CSS规则字符串
document.head.appendChild(style);

TestBody();
ajaxGet();
//关闭
function offT() {
  document.querySelector("#zdy-main").style.display = `none`;
}
//开启
function onT() {
  document.querySelector("#zdy-main").style.display = `flex`;
}
function TestBody() {
  let code = `
        <div id="zdy-main">
            <div class="zdy-bigBox" >
        <!-- 表头 start -->
        <div class="zdy-tableHeader">
            <h5 class="zdy-title">商机信息</h5>
            <div class="zdy-header-button">
                <input type="text" placeholder="请输入关键词">
                <button id="X">X</button>
            </div>
        </div>
        <!-- 表头 end -->

        <!-- Tabs start -->
         <div class="zdy-col-box">
            <ul>
                <li>所有数据</li>
            </ul>
         </div>
         <!-- Tabs end -->

         <!-- 表体 start -->
          <div class="zdy-table-box">
              <table class="zdy-table" id="zdy-table">
                
                  
              </table>
          </div>
         <!-- 表体 end -->
<!--        分页控件 start-->
        <div class="zdy-col-box">
            <p>第1-20条/总共 70条</p>
            <div class="zdy-box-page">
                <button><</button>
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                    <li>4</li>
                </ul>
                <button>></button>
            </div>
        </div>
        <!--        分页控件 end-->
        <div class="zdy-btn-ok">
           <div class="zdy-btn-box">
               <button id="zdy-btn-off">取消</button>
               <button id="zdy-btn-on">确定</button>
           </div>
        </div>
    </div>
        </div>
    `;
  document.querySelector("#root").insertAdjacentHTML("beforeend", code);
  document.querySelector("#zdy-btn-off").addEventListener("click", (e) => {
    offT();
    if (!nodeActive) return;
    nodeActive.classList.remove("zdy-active");
    currentSeleRow = -1;
  });
  document.querySelector("#X").addEventListener("click", (e) => {
    offT();
    if (!nodeActive) return;
    nodeActive.classList.remove("zdy-active");
    currentSeleRow = -1;
  });
  //TODO 缺少字段
  document.querySelector("#zdy-btn-on").addEventListener("click", (e) => {
    // console.log(resData[currentSeleRow]);
    const _data = resData[currentSeleRow];
    if (currentSeleRow !== -1) {
      $NG.updateState((updater) => {
        updater.data.p_form_integrated_apply_m.setProps({
          u_bus_no: _data.field_ub97r__c,
          u_sj_name: _data.name,
          //   u_tar_amt: _data.field_3blb1__c,
        });
      });
      getSjhInfo(_data.field_ub97r__c)
    }
    nodeActive.classList.remove("zdy-active");
    currentSeleRow = -1;
    offT();
  });
}
// 请求服务器
function ajaxGet() {
  const mstform = $NG.getCmpApi("p_form_integrated_apply_m");
  //   console.log("调用ajaxGet");
  if (!mstform || !mstform.getItem("u_pc_pre_sales").getValue()) {
    let str = `
            <h4>获取帮助失败，请重新选择售前</h4>
    `;
    document.querySelector("#zdy-table").innerHTML = str;
    return;
  }
  $NG.execServer("getBusNo", { phid: mstform.getItem("u_pc_pre_sales").getValue() }, (res) => {
    try {
      //#region
      //   console.log(`查找编码`, res);
      if (res.count == 0) {
        let str = `
            <h4>当前项目售前字段数据存在问题，可能是没编码！</h4>
    `;
        document.querySelector("#zdy-table").innerHTML = str;
      }
      const _data = JSON.parse(res.data)[0].extendObjects;
      //发请求
      const xhr = new XMLHttpRequest();
      // xhr.open("POST", "http://nginx.clouddev.hisense.com/sd/sdToCrm/apply/opportunity/query");
      xhr.open("POST", "https://inner-apisix.hisense.com/hisense/sd/crm/sdToCrm/apply/opportunity/query?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6");
      xhr.setRequestHeader("Content-Type", "text/plain"); // 改为简单请求允许的类型
      xhr.send(JSON.stringify({ name: String(_data.bill_no) }));
      // xhr.setRequestHeader("Content-Type", "application/json");
      // xhr.send(
      //   JSON.stringify({
      //     name: String(_data.bill_no),
      //   })
      // );
      let str = `
     <thead>
        <tr class="zdy-table-thead-tr">
            <th>商机编码</th>
            <th>商机名称</th>
            <th>项目金额</th>
            <th>预计签单时间</th>
        </tr>
    </thead>
    <tbody>
    `;
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var response = JSON.parse(xhr.responseText);
          //   console.log("服务器端返回的响应:", response);
          if (response.length == 0) {
            str = `
            <h4>当前项目售前无数据</h4>
            `;
            document.querySelector("#zdy-table").innerHTML = str;
            return;
          }
          resData = response;
          resData.forEach((item) => {
            str += `
                     <tr class="zdy-table-tbody-tr">
                        <td>${item.field_ub97r__c}</td>
                        <td>${item.name}</td>
                        <td>${item.field_3blb1__c}</td>
                        <td>${item.expected_signing_time_text__c}</td>
                    </tr>
                `;
          });
          str += "</tbody></table>";
          // document.querySelector("#zdy-table").addEventListener
          document.querySelector("#zdy-table").innerHTML = ''
          document.querySelector("#zdy-table").insertAdjacentHTML("beforeend", str);
          if (domTRarr) {
            domTRarr.forEach((item) => {
              item.removeEventListener("click", itemFC());
            });
          }
          domTRarr = document.querySelectorAll(".zdy-table-tbody-tr");
          domTRarr.forEach((item, index) => {
            item.addEventListener("click", (e) => {
              itemFC(e, index);
            });
            item.addEventListener("dblclick", () => {
              //   console.log(`双击事件`);
              dbClick();
            });
          });
        } else {
          //   console.log(`状态`, xhr.readyState);
        }
      };
      //#endregion
    } catch (error) {
      //   console.log(error);
    }
  });

  //双击触发事件
  function dbClick() {
    const _data = resData[currentSeleRow];
    currentSeleRow = -1;
    document.querySelector("#zdy-main").style.display = `none`;
    try {
      nodeActive.classList.remove("zdy-active");
    } catch (e) { }
    $NG.updateState((updater) => {
      updater.data.p_form_integrated_apply_m.setProps({
        u_bus_no: _data.field_ub97r__c,
        u_sj_name: _data.name,
        // u_tar_amt: _data.field_3blb1__c,
      });
      getSjhInfo(_data.field_ub97r__c)
    });
  }
  // 点击逻辑
  function itemFC(e, index) {
    currentSeleRow = index;
    // console.log(e, "qf");
    if (e.target instanceof HTMLTableCellElement) {
      const pre = e.target.parentNode;
      if (pre instanceof HTMLTableRowElement) {
        if (nodeActive) {
          nodeActive.classList.remove("zdy-active");
        }
        nodeActive = pre;
        nodeActive.classList.add("zdy-active");
      }
    }
  }
}
